package threadjuc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/27 16:04
 * 线程都操作资源，降低耦合
 */
public class Juc2 {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                buyTicket.buyTickets();
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                buyTicket.buyTickets();
            }
        }).start();

        new Thread(()->{
            for(int i = 0; i < 20; i++) {
            buyTicket.buyTickets();
        }
        }).start();
    }
}

/**
 * 资源 包含属性 方法
 */
class BuyTicket{
    private int num = 20;
    /**
     * 公平锁：先来先执行
     * 非公平锁：可插队（默认）
     * 3h的线程 和 3s的线程
     */
    Lock lock = new ReentrantLock();

    public void buyTickets(){
        lock.lock();  //加锁
        try {
            //业务
            if (num>0){
                System.out.println("卖出了第"+(num)+"张票，剩下"+(--num)+"张票");
            }
        }finally {
            lock.unlock();  //执行完解锁
        }

    }
}
